// pages/oerderDetail.js
// 获取应用实例
const app = getApp()
const $req = require('../../utils/req.js') //接口封装文件
Page({

  /**
   * 页面的初始数据
   */
  data: {
    getOrderInfo:{},

    firstEnter:false,
    scheduleLegend: [{
      name: '可预订',
      color: '#D1D1D1',
    }, {
      name: '不可预订',
      color: '#777575'
    }, {
      name: '已预订',
      color: '#EA5826',
    }, {
      name: '已选中',
      color: '#FDB644',
    }],
    roomInfo: {},
    roomTimes: [],
    goodsList: [],
    totalPrice: '0.00',
    dis: 0,
    disAmount: '0.00',
    goodsListTotalPrice: '0.00',
    finsTotalprice: '0.00',
    timeInterval: [0, 0],
    isIphoneX: app.globalData.systemInfo.screenHeight >= 812 ? true : false,
    bannerList: [{
      url: '../../public/cache/roomImg.png'
    }], //轮播图
  },
  // ===============================================================================
  // ===============================================================================
  getRoomInfo(RoomID) {
    let _this = this
    let data = {
      RoomID: RoomID
    }
    $req.getRoomInfo(data).then(res => {
      _this.setData({
        roomInfo: res.DATA
      })
    })
  },
  // 获取会议室可用时间段
  getRoomTimesInfo(RoomID, Mdate) {
    let _this = this
    let data = {
      RoomID: RoomID,
      Mdate: Mdate,
    }
    $req.getRoomTimesInfo(data).then(res => {
      let result = res.DATA
      result.forEach((item, index) => {
        item.timePoint = item.FromTo.split("-")[0]

      });
      _this.setData({
        roomTimes: result,
        checkFlag: false,
      })
    })
  },

  getGoodsList(RoomID) {
    let _this = this
    let data = {
      RoomID: RoomID,
    }
    $req.getGoodsList(data).then(res => {
      let result = res.DATA
      result.forEach((item, index) => {
        item.num = 0
        item.Price = item.Price.toFixed(2)
        item.totalPrice = (item.Price * item.num).toFixed(2)
      })

      _this.setData({
        goodsList: res.DATA
      })
    })
  },

  // 点击时间表格
  touchTimesTable(e) {
    let _this = this
    let checkTimeIndex = e.currentTarget.dataset.index //用户点击的时间索引
    let typeValue = _this.data.roomInfo.SortNm == "大型会议室" ? 7 : 3 //不算首位
    let roomTiemsCopy = Object.create(_this.data.roomTimes) //拷贝数据
    let timeInterval = _this.data.timeInterval
    if (roomTiemsCopy[checkTimeIndex].checkFlag) {
      // 点击项为选中的
      if ((checkTimeIndex - timeInterval[0]) > typeValue) {
        roomTiemsCopy.forEach((item, index) => {
          item.checkFlag = false
          if (timeInterval[0] <= index && index < checkTimeIndex) {
            timeInterval[0] = timeInterval[0]
            timeInterval[1] = checkTimeIndex
            item.checkFlag = true
          }
        })
      } else {
        // 剩余区间不足最小范围
        roomTiemsCopy.forEach((item, index) => {
          timeInterval[0] = 0
          timeInterval[1] = 0
          item.checkFlag = false
        })
      }
    } else {
      // 点击项为未选择的
      if (timeInterval[0] == 0 && timeInterval[1] == 0) {
        // 初始状态
        if ((checkTimeIndex + typeValue) > roomTiemsCopy.length - 1) {
          // 判断点击点位是否超过可选
          return
        }
        let canCheck = false
        roomTiemsCopy.forEach((item, index) => {
          if (checkTimeIndex <= index && index <= (checkTimeIndex + typeValue)) {
            if (!item.CanOrder || item.IsOrder) {
              canCheck = true
            }
          }
        })
        if (canCheck) {
          return
        }
        roomTiemsCopy.forEach((item, index) => {
          if (checkTimeIndex <= index && index <= (checkTimeIndex + typeValue)) {
            timeInterval[0] = checkTimeIndex
            timeInterval[1] = (checkTimeIndex + typeValue)
            item.checkFlag = true
          }
        })
      } else {
        let canCheck = false

        roomTiemsCopy.forEach((item, index) => {
          if (checkTimeIndex <= index && index <= timeInterval[1]) {
            if (!item.CanOrder || item.IsOrder) {
              canCheck = true
            }
          }
        })

        if (canCheck) {
          return
        }

        // 二次点击
        if (checkTimeIndex < timeInterval[0]) {
          roomTiemsCopy.forEach((item, index) => {
            if (checkTimeIndex <= index && index <= timeInterval[1]) {
              timeInterval[0] = checkTimeIndex
              timeInterval[1] = timeInterval[1]
              item.checkFlag = true
            }
          })
        } else if (checkTimeIndex > timeInterval[1]) {
          roomTiemsCopy.forEach((item, index) => {
            if (timeInterval[0] <= index && index <= checkTimeIndex) {
              timeInterval[0] = timeInterval[0]
              timeInterval[1] = checkTimeIndex
              item.checkFlag = true
            }
          })
        }
      }
    }
    _this.setData({
      roomTimes: roomTiemsCopy,
      timeInr: timeInterval
    })
    _this.totalPrice()
    _this.finsTotalprice()
  },

  // 计算总金额
  totalPrice() {
    let _this = this
    let roomTiemsCopy = Object.create(_this.data.roomTimes)
    let totalPrice = 0
    roomTiemsCopy.forEach((item, index) => {
      if (item.checkFlag) {
        totalPrice += item.Price
      }
    })
    _this.setData({
      totalPrice: (totalPrice).toFixed(2),
      disAmount: (totalPrice * wx.getStorageSync('userInfo').Discount).toFixed(2),
    })
  },

  changeGoodsNum(e) {
    let _this = this
    let data = e.currentTarget.dataset
    let goodsList = _this.data.goodsList
    let goods = goodsList[data.index]
    switch (data.type) {
      case "+":
        goods.num += 1
        break
      case "-":
        goods.num -= 1
        break
    }

    if (goods.num < 0) {
      goods.num = 0
    }

    goods.totalPrice = (goods.num * goods.Price).toFixed(2)

    _this.goodsListTotalPrice()
    _this.finsTotalprice()

    _this.setData({
      goodsList: goodsList,
    })
  },

  finsTotalprice() {
    let _this = this
    _this.setData({
      finsTotalprice: (parseFloat(_this.data.disAmount) + parseFloat(_this.data.goodsListTotalPrice)).toFixed(2),
    })
  },

  goodsListTotalPrice() {
    let _this = this
    let goodsListTotalPrice = 0
    let goodsList = _this.data.goodsList
    goodsList.forEach((item, index) => {
      goodsListTotalPrice += parseFloat(item.totalPrice)
    })

    _this.setData({
      goodsListTotalPrice: goodsListTotalPrice.toFixed(2)
    })
  },


  saveOrder() {
    let _this = this
    let data = {
      Token: wx.getStorageSync("userInfo") ? wx.getStorageSync("userInfo").token : '',
      OrderNo: '', //	string	订单编号(新订单为空)
      RoomID: _this.data.roomInfo.RoomID,
      Mdate: '2021-06-24', //date	会议室预订日期(开始日期）
      MdateTo: '2021-06-24', //	date	会议室预订日期(结束日期）
      Descr: '', //	string	订单备注
      Details: [], //	Json	列表
      Goods: [], // Goods 商品
    }

    _this.data.goodsList.forEach((item, index) => {
      data.Goods.push({
        GoodsID: item.GoodsID,
        Nums: item.num
      })
    })

    _this.data.roomTimes.forEach((item, index) => {
      if (item.checkFlag) {

        data.Details.push({
          Mdate: item.Mdate,
          TimesID: item.TimesID,
        });
      }
    })




    $req.saveOrder(data).then(res => {
      console.log(res)
      wx.navigateTo({
        url: '../completeOrder/completeOrder?orderNo=' + res.DATA.OrderNo,
        // success: (res) => {
        //   mta.Event.stat('FirstClassName(' + e.currentTarget.dataset.name + ')', {
        //     "firstclassid": e.currentTarget.dataset.id
        //   })
        // }
      })
      // 
    })
  },


  // ===============================================================================
  // ===============================================================================
  // ===============================================================================
  /* 小程序1.0版本
   * 选择店铺后返回上一级
   */
  navigateBack() {
    wx.navigateBack({
      delta: 1
    })
  },

  getOrderInfo(OrderNo){
    let _this = this
    let data={
      Token:wx.getStorageSync("userInfo") ? wx.getStorageSync("userInfo").token : '',
      OrderNo:OrderNo
    }
    $req.getOrderInfo(data).then(res=>{
      res.DATA[0].GoodsList.forEach((item, index) => {
        item.Price = item.Price.toFixed(2)
        item.totalPrice = (item.Price * item.Nums).toFixed(2)
      })


      _this.setData({
        orderInfo:res.DATA[0]
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this = this
  
    _this.getOrderInfo(options.orderNo)
    // _this.getRoomTimesInfo(options.id, '2021-06-24')
    // _this.getGoodsList(options.id)
    // _this.setData({
    //   dis: wx.getStorageSync('userInfo').Discount,
    // })
    

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _this = this
    if(_this.data.firstEnter){
      _this.getGoodsList(_this.data.roomInfo.RoomID)
      _this.getRoomTimesInfo(_this.data.roomInfo.RoomID, '2021-06-24')
    }

    _this.setData({
      firstEnter:true
    })

   
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})